﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using STLGROUP.Layers.Presentations.FormBase;
using STLGROUP.Layers.BLL;
using STLGROUP.Layers.Common;
using STLGROUP.Layers.DataAccessLayers;

namespace QuanLyBanHang
{
    /// <summary>
    /// MF004 - Quan ly san pham
    /// </summary>
    /// <author>viet sang</author>
    /// <date>15/04/2012</date>
    public partial class MF004 : frmManager
    {
        #region Variables

        DT_SanPhamBLL _business;
        DT_SanPham _current;

        ToolStripButton _btnCapNhatTrangThai;
        ToolStripButton _btnInMaVach;

        private static int _idSanPham; //Add by VanLong - date 17/06/2012
        public static bool _isShowButtonChon = false; //Add by VanLong - date 17/06/2012

        #endregion

        #region Contructors

        public MF004()
        {
            InitializeComponent();
            InitializeForm();
        }

        #endregion

        #region Private methods

        private void InitializeForm()
        {
            if (_isShowButtonChon) //Add by VanLong - date 17/06/2012
            {
                DataGridViewButtonColumn colButtonChon = new DataGridViewButtonColumn();
                colButtonChon.HeaderText = "Lựa chọn";
                colButtonChon.Text = "Chọn";
                colButtonChon.UseColumnTextForButtonValue = true;
                colButtonChon.Width = 80;

                dgvSanPham.Columns.Add(colButtonChon);
            }

            _business = new DT_SanPhamBLL();
            UICommon.AddTrackingColumn(dgvSanPham);

            this.dgvSanPham.DataError += new DataGridViewDataErrorEventHandler(dgvSanPham_DataError);
            this.dgvSanPham.RowPostPaint += new DataGridViewRowPostPaintEventHandler(dgvSanPham_RowPostPaint);

            this._bindingSource.CurrentChanged += new EventHandler(_bindingSource_CurrentChanged);
            this.picHinhAnh.Click += new EventHandler(picHinhAnh_Click);

            //add controls
            this._btnCapNhatTrangThai = new ToolStripButton();
            this._btnCapNhatTrangThai.AutoSize = true;
            this._btnCapNhatTrangThai.ForeColor = System.Drawing.Color.Black;
            //this._btnCapNhatTrangThai.Image = global::STLGROUP.Layers.Properties.Resources.process;
            this._btnCapNhatTrangThai.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._btnCapNhatTrangThai.Name = "tsbCapNhatTrangThai";
            this._btnCapNhatTrangThai.Padding = new System.Windows.Forms.Padding(3, 0, 4, 0);
            //this._btnCapNhatTrangThai.Size = new System.Drawing.Size(150,27);
            this._btnCapNhatTrangThai.Text = "Cập nhật trạng thái";
            this._btnCapNhatTrangThai.Visible = true;
            _btnCapNhatTrangThai.Click += new EventHandler(_btnCapNhatTrangThai_Click);


            //add controls
            this._btnInMaVach = new ToolStripButton();
            this._btnInMaVach.AutoSize = true;
            this._btnInMaVach.ForeColor = System.Drawing.Color.Black;
            this._btnInMaVach.ImageTransparentColor = System.Drawing.Color.Magenta;
            this._btnInMaVach.Name = "btnInMaVach";
            this._btnInMaVach.Padding = new System.Windows.Forms.Padding(3, 0, 4, 0);
            this._btnInMaVach.Text = "In mã vạch";
            this._btnInMaVach.Visible = true;
            _btnInMaVach.Click += new EventHandler(_btnInMaVach_Click);


            toolStrip1.Items.Insert(8, _btnCapNhatTrangThai);
            toolStrip1.Items.Insert(9, _btnInMaVach);
        }
        
        #endregion

        #region Protected methods

        protected override void LoadData()
        {
            this._bindingSource.DataSource = Cache.Context.DT_SanPham;
            this.dgvSanPham.DataSource = _bindingSource;
            base.LoadData();
        }

        protected override void ImportFormExcel()
        {
            ImportDataFromExcel<DT_SanPham>(dgvSanPham);
        }

        protected override void ExportToExcel()
        {
            ExportDataToExcel(dgvSanPham);
        }

        protected override void AddDataBinding()
        {
            txtMaSanPham.DataBindings.Add(Const.BIND_TEXT, _bindingSource, "MaSanPham", true);
            txtTenSanPham.DataBindings.Add(Const.BIND_TEXT, _bindingSource, "TenSanPham", true);
            txtSoLuong.DataBindings.Add(Const.BIND_VALUE, _bindingSource, "SoLuongNhapThem", true);
            txtGiaNhap.DataBindings.Add(Const.BIND_VALUE, _bindingSource, "GiaNhap", true);
            txtGiaSi.DataBindings.Add(Const.BIND_VALUE, _bindingSource, "GiaBanSi", true);
            txtGiaLe.DataBindings.Add(Const.BIND_VALUE, _bindingSource, "GiaBanLe", true);
            txtSoLuongCanhBao.DataBindings.Add(Const.BIND_VALUE, _bindingSource, "SoLuongCanhBao", true);
            txtDonViTienTe.DataBindings.Add(Const.BIND_TEXT, _bindingSource, "DonViTienTe", true);
            txtMoTa.DataBindings.Add(Const.BIND_TEXT, _bindingSource, "MoTa", true);
            //picHinhAnh.DataBindings.Add(Const.BIND_IMAGE, _bindingSource, "HinhAnh", true);

            cboDonViTinh.DataSource = Cache.Context.DM_DonViTinh;
            cboDonViTinh.DisplayMember = "TenDonViTinh";
            cboDonViTinh.ValueMember = "IDDonViTinh";
            cboDonViTinh.DataBindings.Add(Const.BIND_SELECTED_VALUE, _bindingSource, "IDDonViTinh", true);

            DonViTinh.DataSource = Cache.Context.DM_DonViTinh;
            DonViTinh.DisplayMember = "TenDonViTinh";
            DonViTinh.ValueMember = "IDDonViTinh";

            cboLoaiSanPham.DataSource = Cache.Context.DM_LoaiSanPham;
            cboLoaiSanPham.ValueMember = "IDLoaiSanPham";
            cboLoaiSanPham.DisplayMember = "TenLoaiSanPham";
            cboLoaiSanPham.DataBindings.Add(Const.BIND_SELECTED_VALUE, _bindingSource, "IDLoaiSanPham", true);

            LoaiSanPham.DataSource = Cache.Context.DM_LoaiSanPham;
            LoaiSanPham.ValueMember = "IDLoaiSanPham";
            LoaiSanPham.DisplayMember = "TenLoaiSanPham";

            cboNhaCungCap.DataSource = Cache.Context.DT_NhaCungCap;
            cboNhaCungCap.ValueMember = "IDNhaCungCap";
            cboNhaCungCap.DisplayMember = "TenNhaCungCap";
            cboNhaCungCap.DataBindings.Add(Const.BIND_SELECTED_VALUE, _bindingSource, "IDNhaCungCap", true);

            NhaCungCap.DataSource = Cache.Context.DT_NhaCungCap;
            NhaCungCap.DisplayMember = "TenNhaCungCap";
            NhaCungCap.ValueMember = "IDNhaCungCap";

            base.AddDataBinding();
        }

        protected override void RefreshData()
        {
            LoadData();
            base.RefreshData();
            UICommon.ShowDataNotFound(dgvSanPham, lblTimKiem, false);
        }

        protected override void AddNew()
        {
            base.AddNew();
            txtGiaNhap.Value = 0;
            txtGiaLe.Value = 0;
            txtGiaSi.Value = 0;
            txtSoLuong.Value = 0;
            txtSoLuongCanhBao.Value = 0;
            txtSoLuong.Enabled = true;
            txtTenSanPham.Focus();

        }

        protected override int UpdateData()
        {
            if (base.UpdateData() > 0)
            {
                IQueryable<DT_SanPham> lstData = this._bindingSource.DataSource as IQueryable<DT_SanPham>;
                _business.UpdateSanPham(lstData);
                return base.UpdateData();
            }
            //LoadData();

            return -1;

        }
        
        protected override void Search()
        {
            var data = from c in Cache.Context.DT_SanPham
                       where c.MaSanPham.Contains(tscbxTimKiem.Text) ||
                       c.TenSanPham.Contains(tscbxTimKiem.Text) ||
                       c.MoTa.Contains(tscbxTimKiem.Text)                       
                       select c;

            List<DT_SanPham> lstData = data.ToList<DT_SanPham>();

            //Hien thi thong bao khi khong tim thay du lieu
            UICommon.ShowDataNotFound(dgvSanPham, lblTimKiem, lstData.Count == 0);

            _bindingSource.DataSource = data;
            dgvSanPham.DataSource = _bindingSource;

        }

        protected override void Edit()
        {
            base.Edit();
            txtSoLuong.Enabled = false;
        }

        protected override void Delete()
        {
            DT_SanPham sp = _bindingSource.Current as DT_SanPham;
            if (sp == null || sp.SoLuongTonKho > 0)
            {
                UICommon.ShowMessegeInfo(Const.MSG_KHONG_XOA_VI_SLUONG_LON_HON_KHONG);
                return;
            }
            else
            {
                sp.IDTrangThaiSanPham = (int?)StructsEnums.EnumTrangThaiSanPham.Huy;
            }

        }

        #endregion

        #region Public Methods

        public static int GetIDSanPham() //Add by VanLong - date 17/06/2012
        {
            return _idSanPham;
        }

        #endregion

        #region Events

        private void dgvSanPham_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView dg = (DataGridView)sender;
            // Current row record
            string rowNumber = (e.RowIndex + 1).ToString();

            // Format row based on number of records displayed by using leading zeros
            while (rowNumber.Length < dg.RowCount.ToString().Length)
            {
                rowNumber = "0" + rowNumber;
            }

            // Position text
            SizeF size = e.Graphics.MeasureString(rowNumber, this.Font);
            if (dg.RowHeadersWidth < (int)(size.Width + 20))
            {
                dg.RowHeadersWidth = (int)(size.Width + 20);
            }

            // Use default system text brush
            Brush b = SystemBrushes.ControlText;

            // Draw row number
            e.Graphics.DrawString(rowNumber, dg.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2));
        }

        private void dgvSanPham_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            
        }

        private void _bindingSource_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                _current = (DT_SanPham)_bindingSource.Current;

                //showbarcode
                stlBarCodeCtrl1.BarCode = _current.MaSanPham;

                if (_current.HinhAnh != null)
                {
                    UICommon.ShowImage(UICommon.ByteArrayToImage(_current.HinhAnh), picHinhAnh);
                }
                else
                {
                    UICommon.ShowImage(QuanLyBanHang.Properties.Resources.click_chon_anh, picHinhAnh);
                }
            }
            catch
            {
                _current = null;
            }
        }

        private void picHinhAnh_Click(object sender, EventArgs e)
        {
            if (_current == null)
            {
                UICommon.ShowMessegeInfo(Const.MSG_CHUA_CHON_SAN_PHAM);
                return;
            }

            OpenFileDialog open = new OpenFileDialog();
            open.Title = "Vui lòng chọn file hình ảnh";
            //open.InitialDirectory = "('*.jpg'||('*.jpg'))";
            open.Multiselect = false;

            DialogResult result = open.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                Image img = UICommon.AddImage(open.FileName,Const.MAX_IMAGE);
                if (img != null)
                {
                    picHinhAnh.Image = img;
                    _current.HinhAnh = UICommon.ImageToByteArray(img);
                }
            }
            else
            {
                picHinhAnh.Image = null;
            }
        }

        private void btnNhaCungCap_Click(object sender, EventArgs e)
        {
            UICommon.ShowPopup(new MF002(){WindowState = FormWindowState.Normal}, StructsEnums.EnumDanhMuc.NhaCungCap, cboNhaCungCap, NhaCungCap);
        }

        private void btnLoaiSanPham_Click(object sender, EventArgs e)
        {
            UICommon.ShowPopup(new CF003(), StructsEnums.EnumDanhMuc.LoaiSanPham, cboLoaiSanPham, LoaiSanPham);
        }

        private void _btnCapNhatTrangThai_Click(object sender, EventArgs e)
        {
            if (_current != null)
            {
                PF001 frm = new PF001() { SanPham = _current, Context = Cache.Context };
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Cache.Context.SaveChanges();
                }
            }
        }

        private void _btnInMaVach_Click(object sender, EventArgs e)
        {
            if (_current != null)
            {
                PF002 frm = new PF002() { SanPham = _current };
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {                    
                    //Cache.Context.SaveChanges();
                }
            }
        }

        //Add by VanLong - date 17/06/2012
        private void dgvSanPham_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == Const.INDEX_COLUMN_CHON_SAN_PHAM)
                {
                    _idSanPham = ((DT_SanPham)(_bindingSource.Current)).IDSanPham;

                    this.Close();
                }
                else
                {
                    _idSanPham = 0;
                }
            }
            catch
            {
                _idSanPham = 0;
            }
        }

        #endregion

        private void txtSoLuong_ValueChanged(object sender, EventArgs e)
        {
            
        }
    }
}
